import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:joyagoo/request/LoadingUtil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../config/app_colors.dart';
import '../utils/JoyActionService.dart';
import '../utils/JoyBlocUtil.dart';
import '../utils/JoyCacheManager.dart';
import '../utils/JoyUrlLauncherService.dart';
import '../utils/route_utils.dart';
import 'JoyAboutUsPage.dart';
import 'joy_collection_page.dart';
import 'joy_home_bloc.dart';
import 'joy_login_page.dart';
import 'joy_forgot_password_page.dart';
import 'joyHistoryBrowsePage.dart';
import 'JoyPrivacyWebPage.dart';

class JoyProfilePage extends StatefulWidget {
  const JoyProfilePage({super.key});

  @override
  State<JoyProfilePage> createState() => _JoyProfilePageState();
}

class _JoyProfilePageState extends State<JoyProfilePage> {
  bool _isLoggedIn = false;
  String _userAccount = '';
  String _password = '';

  int _likeCount = 0;
  String _appVersion = '1.0.0';
  late JoyHomeBloc loginBloc;
  int postType = 0;

  @override
  void initState() {
    super.initState();
    _loadUserData();
    _getAppVersion();
  }

  Future<void> _loadUserData() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
      _userAccount = prefs.getString('userAccount') ?? '';
      _password = prefs.getString('userPassword') ?? '';
    });
  }

  Future<void> _getAppVersion() async {
    try {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      setState(() {
        _appVersion = packageInfo.version;
      });
    } catch (e) {
      // 如果获取失败，保持默认版本号
      debugPrint('获取应用版本号失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      body: BLocLogin(),
    );
  }

  Widget settingView(){
    return Column(
      children: [
        // 顶部用户信息区域
        _buildUserSection(),

        Visibility(
          child: _buildQuickAccessSection(),
          visible: _isLoggedIn,
        ),
        SizedBox(height: 8.h),

        // 🔥 使用Expanded让功能菜单区域填满剩余空间
        Expanded(
          child: SingleChildScrollView(
            child: _buildFunctionSection(),
          ),
        ),
      ],
    );
  }
  Widget BLocLogin(){
    return JoyBlocUtil.getAppNoBarBloc(builder: (context, state) {
      return settingView();
    }, create: (_) {
      loginBloc = JoyHomeBloc();

      return loginBloc;
    }, buildWhen: (previousState, state) {
      if(state is postUserLoginOutEventSuccess){

        if(postType == 1){
          // 退出登录
          cleanAccount();
        }
        if(postType == 2){
          // 注销账号
          cleanAccount();
        }
        Navigator.pop(context);

        return true;
      }
      if(state is postUserLoginOutEventFailure){
        String msg = state.errMsg??"net error";
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(msg)),
        );
        return true;

        return true;
      }

      return false;
    });
  }

  Future<void> cleanAccount() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear();
    setState(() {
      _isLoggedIn = false;
      _userAccount = '';
      _likeCount = 0;
    });
  }


  // 构建用户信息区域
  Widget _buildUserSection() {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            AppColors.backHomeYellowGround,
            AppColors.backHomeYellowGround,
          ],
        ),
      ),
      child: SafeArea(
        child: Column(
          children: [
            SizedBox(height: 8.h),
            
            // 用户头像和信息
            if (_isLoggedIn) ..._buildLoggedInUser() else ..._buildLoginPrompt(),
            
            SizedBox(height: 10.h),
          ],
        ),
      ),
    );
  }

  // 构建快捷入口区域
  Widget _buildQuickAccessSection() {
    return Stack(
      children: [
        Container(
          height: 80,
          decoration: BoxDecoration(
            color: AppColors.backHomeYellowGround,
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20),bottomRight: Radius.circular(20))
          ),
          
        ),
        showThree(),
      ],
    );
  }

  Widget showThree(){
    return Container(
      margin: EdgeInsets.only(left: 23,right: 23),
      padding: EdgeInsets.only(top: 23,bottom: 23),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(10)),
        boxShadow: [
          
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildQuickAccessItem(
            imagePath: 'images/icon_Favorites.png',
            icon: Icons.favorite_outline,
            label: 'Favorites',
            onTap: _navigateToMyFavorites,
          ),
          _buildQuickAccessItem(
            imagePath: 'images/icon_History.png',
            icon: Icons.access_time,
            label: 'History',
            onTap: _navigateToHistoryBrowse,
          ),
          _buildQuickAccessItem(
            imagePath: 'images/icon_Order.png',
            icon: Icons.list_alt,
            label: 'Order',
            onTap: _navigateToOrders,
          ),
        ],
      ),
    );
  }


  // 构建单个快捷入口项
  Widget _buildQuickAccessItem({
    String? imagePath,
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.opaque,
      child: Container(
        width: 80.w,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 图标容器
            Container(
              width: 44.w,
              height: 44.w,
              decoration: BoxDecoration(
                color: AppColors.primary,
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: Center(
                child: imagePath != null && imagePath.isNotEmpty
                    ? Image.asset(
                        imagePath,
                        width: 44.w,
                        height: 44.w,
                        fit: BoxFit.contain,
                        // color: AppColors.backHomeYellowGround,
                        errorBuilder: (context, error, stackTrace) {
                          return Icon(
                            icon,
                            size: 28.sp,
                            color: AppColors.backHomeYellowGround,
                          );
                        },
                      )
                    : Icon(
                        icon,
                        size: 28.sp,
                        color: AppColors.backHomeYellowGround,
                      ),
              ),
            ),
            SizedBox(height: 8.h),
            // 标签文字
            Text(
              label,
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.black87,
                fontWeight: FontWeight.w500,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  // 已登录用户信息
  List<Widget> _buildLoggedInUser() {
    return [
      // 头像
      Container(
        width: 50.w,
        height: 50.w,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(30.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Icon(
          Icons.person,
          size: 30.sp,
          color: AppColors.primary,
        ),
      ),
      
      SizedBox(height: 8.h),
      
      // 用户账号
      Text(
        _userAccount,
        style: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w500,
          color: Colors.white,
        ),
      ),
      SizedBox(height: 4.h),
    ];
  }

  // 未登录提示
  List<Widget> _buildLoginPrompt() {
    return [
      // 默认头像
      Container(
        width: 50.w,
        height: 50.w,
        decoration: BoxDecoration(
          color: AppColors.backHomeYellowGround,
          borderRadius: BorderRadius.circular(30.r),
        ),
        child: Image.asset("images/icon_Vector.png"),
      ),
      
      SizedBox(height: 6.h),

      Container(
        margin: EdgeInsets.only(top: 10.w,bottom: 10.w),
        child: Text(
          'Login to view more information',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 10.sp,
            fontWeight: FontWeight.normal,
            color: AppColors.textSecondary,

          ),
        ),
      ),
      
      // 登录按钮
      GestureDetector(
        onTap: _navigateToLogin,
        child: Container(
          width: ScreenUtil().screenWidth - 80.w,
          padding: EdgeInsets.symmetric( vertical: 10.h),
          decoration: BoxDecoration(
            color: AppColors.primaryVariant,
            borderRadius: BorderRadius.circular(5.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 6,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Text(
            'Login/Register',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.bold,
              color: AppColors.backHomeYellowGround,

            ),
          ),
        ),
      ),
    ];
  }

  // 小型操作按钮
  Widget _buildSmallActionButton({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.2),
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color: Colors.white.withOpacity(0.3),
            width: 1,
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              size: 16.sp,
              color: Colors.white,
            ),
            SizedBox(width: 6.w),
            Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.white,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建功能菜单区域
  Widget _buildFunctionSection() {
    return Column(
      mainAxisSize: MainAxisSize.min, // 🔥 关键修复：使用 min 而不是 max
      children: [
        Container(
          margin: EdgeInsets.symmetric(horizontal: 8.w),
          decoration: BoxDecoration(
            color: Colors.white,
            // borderRadius: BorderRadius.circular(16.r),
            // boxShadow: [
            //   BoxShadow(
            //     color: Colors.black.withOpacity(0.05),
            //     blurRadius: 10,
            //     offset: const Offset(0, 2),
            //   ),
            // ],
          ),
          child: Column(

            children: [

              _buildMenuItem(
                icon: Icons.language,
                title: 'Official Website',
                onTap: _navigateToOfficialWebsite,
              ),
              _buildDivider(),
              _buildMenuItem(
                imagePath: "images/icon_Version_Update.png",
                icon: Icons.system_update,
                title: 'Version Update',
                onTap: _checkUpdate,
              ),
              _buildDivider(),
              _buildMenuItem(
                imagePath: "images/icon_Rate_Us.png",
                icon: Icons.thumb_up_outlined,
                title: 'Rate Us',
                onTap: _likeApp,
              ),
              // _buildDivider(),
              // _buildMenuItem(
              //   icon: Icons.favorite_outline,
              //   title: 'Favorites',
              //   onTap: _navigateToMyFavorites,
              // ),
              // _buildDivider(),
              // _buildMenuItem(
              //   icon: Icons.shopping_bag_outlined,
              //   title: 'Browsing History',
              //   onTap: _navigateToHistoryBrowse,
              // ),
              //  _buildDivider(),
              // _buildMenuItem(
              //   icon: Icons.shopping_bag_outlined,
              //   title: 'Order',
              //   onTap: _navigateToOrderPage,
              // ),
              _buildDivider(),
              _buildMenuItem(
                icon: Icons.info_outline,
                title: 'About Us',
                onTap: _showAboutDialog,
              ),
             
              // 只在已登录状态下显示删除账号选项
              if (_isLoggedIn) ...[
                _buildDivider(),
                _buildMenuItem(
                  icon: Icons.delete_forever_outlined,
                  imagePath: "images/icon_Delete_Account.png",
                  title: 'Delete Account',
                  onTap: _showDeleteAccountDialog,
                  iconColor: Colors.red,
                  titleColor: Colors.red,
                ),
              ],
            ],
          ),
        ),
        
        // 只在已登录状态下显示退出登录按钮
        if (_isLoggedIn) ...[
          SizedBox(height: 16.h), // 🔥 使用固定间距代替 Spacer
          Container(
            margin: EdgeInsets.fromLTRB(16.w, 0, 16.w, 20.h),
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _logout,
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.backHomeYellowGround,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
                padding: EdgeInsets.symmetric(vertical: 14.h),
                elevation: 1,
              ),
              child: Text(
                'Log Out',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  color: AppColors.primary,
                ),
              ),
            ),
          ),
        ] else ...[
          // 🔥 未登录状态也增加底部间距
          SizedBox(height: 20.h),
        ],
      ],
    );
  }

  // 菜单项
  Widget _buildMenuItem({
    IconData? icon,
    String? imagePath, // 🔥 新增：本地图片路径参数
    required String title,
    String? subtitle,
    required VoidCallback onTap,
    Color? iconColor,
    Color? titleColor,
  }) {
    final itemIconColor = iconColor ?? Colors.grey[600]!;
    final itemTitleColor = titleColor ?? Colors.black87;
    
    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.opaque, // 确保整个区域都能响应点击
      child: Container(
        color: Color(0xFFFAF9F9),
        width: double.infinity, // 确保容器占满整个宽度
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h), // 增加垂直padding从12.h到16.h
        child: Row(
          children: [
            // 🔥 优先使用图片，如果没有图片则使用 icon
            if (imagePath != null && imagePath.isNotEmpty)
              Image.asset(
                imagePath,
                width: 16.sp,
                height: 16.sp,
                fit: BoxFit.contain,
                errorBuilder: (context, error, stackTrace) {
                  // 如果图片加载失败，显示默认 icon
                  return Icon(
                    icon ?? Icons.image_not_supported,
                    size: 16.sp,
                    color: itemIconColor,
                  );
                },
              )
            else
              Icon(
                icon ?? Icons.help_outline,
                size: 16.sp,
                color: itemIconColor,
              ),
            SizedBox(width: 8.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 13.sp,
                      fontWeight: FontWeight.w500,
                      color: itemTitleColor,
                    ),
                  ),
                  if (subtitle != null) ...[
                    SizedBox(height: 1.h),
                    Text(
                      subtitle!,
                      style: TextStyle(
                        fontSize: 10.sp,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ],
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 11.sp,
              color: Colors.grey[400],
            ),
          ],
        ),
      ),
    );
  }

  // 分割线
  Widget _buildDivider() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 18.w),
      height: 13,
      color: Colors.white,
    );
  }

  // 跳转到登录页面
  void _navigateToLogin() async {
    JoyNavUtils().to(JoyLoginPage())?.then((value){
      if(value != null){
        if(value == "successful"){
          _loadUserData();
        }
      }
    });

  }

  // 跳转到我的收藏页面
  void _navigateToMyFavorites() {
    if (!_isLoggedIn) {
      // 未登录，显示登录提示
      _showLoginRequiredDialog('favorites');
      return;
    }
    
    // 已登录，跳转到收藏页面
    JoyNavUtils().to(JoyCollectionPage());
  }

  // 跳转到浏览记录页面
  void _navigateToHistoryBrowse() {
    if (!_isLoggedIn) {
      // 未登录，显示登录提示
      _showLoginRequiredDialog('browsing history');
      return;
    }
    
    // 已登录，跳转到浏览历史页面
    JoyNavUtils().to(JoyHistoryBrowsePage());
  }



  // 退出登录
  Future<void> _logout() async {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        title: Text(
          'Log Out',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        content: const Text('Are you sure you want to log out?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: TextStyle(
                color: Colors.grey[600],
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              loginOutAccount();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.primary,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
            child: Text(
              'Confirm',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 显示注销账号对话框
  void _showDeleteAccountDialog() {
    final TextEditingController passwordController = TextEditingController();
    bool _obscurePassword = true;

    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          backgroundColor: Colors.transparent,
          contentPadding: EdgeInsets.zero,
          content: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16.r),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 20,
                  offset: Offset(0, 10),
                ),
              ],
            ),
            padding: EdgeInsets.all(24.w),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题
                Text(
                  'Delete Account',
                  style: TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                SizedBox(height: 16.h),
                
                // 警告信息
                Text(
                  'After deleting your account, all of your data will be permanently deleted and cannot be recovered.',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[600],
                    height: 1.4,
                  ),
                ),
                SizedBox(height: 20.h),
                
                // 密码提示
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        'Please enter your password to confirm:',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.black87,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Icon(
                      _obscurePassword ? Icons.visibility_off : Icons.visibility,
                      size: 16.sp,
                      color: Colors.grey[500],
                    ),
                  ],
                ),
                SizedBox(height: 12.h),
                
                // 密码输入框
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(color: Colors.grey[300]!),
                    color: Colors.grey[50],
                  ),
                  child: TextField(
                    controller: passwordController,
                    obscureText: _obscurePassword,
                    decoration: InputDecoration(
                      hintText: 'Enter password',
                      hintStyle: TextStyle(
                        color: Colors.grey[500],
                        fontSize: 14.sp,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                      suffixIcon: GestureDetector(
                        onTap: () {
                          setState(() {
                            _obscurePassword = !_obscurePassword;
                          });
                        },
                        child: Icon(
                          _obscurePassword ? Icons.visibility_off : Icons.visibility,
                          color: Colors.grey[500],
                          size: 20.sp,
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 24.h),
                
                // 按钮区域
                Row(
                  children: [
                    // Cancel 按钮
                    Expanded(
                      child: Container(
                        height: 44.h,
                        child: ElevatedButton(
                          onPressed: () => Navigator.pop(context),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: AppColors.primary,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.r),
                            ),
                            elevation: 0,
                          ),
                          child: Text(
                            'Cancel',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 12.w),
                    // Confirm Delete 按钮
                    Expanded(
                      child: Container(
                        height: 44.h,
                        child: ElevatedButton(
                          onPressed: () {
                            _deleteAccount('', passwordController.text);
                            Navigator.pop(context);
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Color(0xFFCACACA),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.r),
                            ),
                            elevation: 0,
                          ),
                          child: Text(
                            'Confirm Delete',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }


  Future<void> loginOutAccount() async {
    final prefs = await SharedPreferences.getInstance();
    final savedPassword = prefs.getString('userPassword') ?? '';
    postType = 1;
    loginBloc.add(PostJOYUserLoginOutEvent(context,_userAccount,savedPassword,"1"));
  }

  // 注销账号
  Future<void> _deleteAccount(String account, String password) async {
    final prefs = await SharedPreferences.getInstance();
    final savedPassword = prefs.getString('userPassword') ?? '';
    
    if (password != savedPassword) {
      _showSnackBar('Account or password verification failed');
      return;
    }

    postType = 2;
    loginBloc.add(PostJOYUserLoginOutEvent(context,_userAccount,password,"2"));
    // await prefs.clear();
    //
    // setState(() {
    //   _isLoggedIn = false;
    //   _userAccount = '';
    //   _likeCount = 0;
    // });
    //
    // _showSnackBar('账号已注销');
  }

  // 显示关于我们对话框
  void _showAboutDialog() {

    JoyNavUtils().to(JoyAboutUsPage());
  }


  // 点赞应用
  Future<void> _likeApp() async {
    JoyActionService.openAppLitStoreRating();

  }

  // 检查版本更新
  void _checkUpdate() {
    JoyActionService.openLitAppStore();
  }


  // 跳转到订单页面
  void _navigateToOrders() {
    // 跳转到订单页面
    _navigateToOrderPage();

  }

  // 显示登录提示对话框
  void _showLoginRequiredDialog(String feature) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFFFAF9F7), // 米白色背景
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        title: Row(
          children: [
            Icon(
              Icons.login,
              color: AppColors.primary,
              size: 24.sp,
            ),
            SizedBox(width: 8.w),
            Text(
              'Login Required',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: AppColors.primary,
              ),
            ),
          ],
        ),
        content: Text(
          'Please log in to access your $feature. You can view all your saved items after logging in.',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.black,
            height: 1.4,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 14.sp,
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              // 导航到登录页面
              _navigateToLogin();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor:  AppColors.primary,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
              elevation: 0,
            ),
            child: Text(
              'Login',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 显示提示消息
  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: const Color(0xFFFF6B35),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
      ),
    );
  }

  // 跳转到订单跟踪页面
  void _navigateToOrderPage() {
    // 在App内打开订单跟踪网页
    JoyNavUtils().to(JoyPrivacyWebPage(
      url: 'https://cnfanss.shop/platform',
      title: 'Order Tracking',
    ));
  }

  // 跳转到官网
  void _navigateToOfficialWebsite() {
    // 使用浏览器打开官网
    JoyActionService.LitopenInSystemAppBrowser('https://litbuy.com/');
  }
}